package pl.un4giv3n.mightvsmagic.action;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.entity.FightReport;
import pl.un4giv3n.mightvsmagic.entity.User;

/**
 * @author andrzejewskia
 * shows all fights performed by user in last week
 */
public class ShowFightsPageAction extends PersistenceAction{

	private static final long serialVersionUID = 1L;
	private User user;
	private List<FightReport> fights;
	private boolean showDefenses;
	
	@SuppressWarnings("unchecked")
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		if(showDefenses){
			Query query = entityManager.createNamedQuery("find.user.defenses");
			query.setParameter("id", user.getId());
			query.setParameter("time", System.currentTimeMillis() - ONE_WEEK);
			fights = query.getResultList();
		}else{
			Query query = entityManager.createNamedQuery("find.user.attacks");
			query.setParameter("id", user.getId());
			query.setParameter("time", System.currentTimeMillis() - ONE_WEEK);
			fights = query.getResultList();
		}
		Collections.sort(fights, new Comparator<FightReport>(){

			@Override
			public int compare(FightReport o1, FightReport o2) {
				long o1exp = o1.getFightTime();
				long o2exp = o2.getFightTime();
				return (o1exp<o2exp ? 1 : (o1exp==o2exp ? 0 : -1));
			}
			
		});
		entityManager.close();
		return SUCCESS;
	}
	
	public List<FightReport> getFights() {
		return fights;
	}
	public boolean isShowDefenses() {
		return showDefenses;
	}
	public void setShowDefenses(boolean showDefenses) {
		this.showDefenses = showDefenses;
	}
	
}
